package com.guoguo.base;

import com.guoguo.entity.Task;
import com.guoguo.utils.ClazzUtils;
import com.guoguo.utils.PropertyUtils;
import com.guoguo.utils.QuartzUtils;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Properties;

/**
 *
 */
public class InitServlet extends HttpServlet {
    private static final long serialVersionUID = -5652071148837106939L;
    private Logger log = LoggerFactory.getLogger(InitServlet.class);

    /**
     * 系统启动时，定时任务调度入口。
     *
     * @throws ServletException
     */
    @Override
    public void init() throws ServletException {
        log.info("==================启动Quartz...");
        InputStream in = PropertyUtils.class.getClassLoader().getResourceAsStream("job.properties");
        Properties props = new Properties();

        try {
            props.load(in);
            Enumeration enumeration = props.propertyNames();
            while (enumeration.hasMoreElements()) {
                //分割定时器配置
                String[] name = props.getProperty(String.valueOf(enumeration.nextElement())).split(":");
                log.info("=========  Quartz Name = job_" + name[0] + "       Trigger Name = trigger_" + name[0]);

                Task task = new Task();
                task.setTaskName("job_" + name);
                task.setTaskGroup("trigger_" + name);
                task.setCronExpression(name[1]);
                task.setClassName(name[0]);
//                task.set

//                QuartzUtils.addJob("job_" + name, "trigger_" + name, ClazzUtils.getEntityClass(name[0]), Integer.valueOf(name[1]));
                QuartzUtils.addJob(task);
            }
        } catch (SchedulerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 系统关闭时，关闭定时任务
     */
    @Override
    public void destroy() {
        log.info("==================停止Quartz...");
        try {
            QuartzUtils.removeJob();
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }
}
